<!DOCTYPE html>
<!--[if lt IE 7 ]> <html lang="en" class="no-js ie6"
                    itemscope itemtype="http://schema.org/Product"> <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="no-js ie7"
                    itemscope itemtype="http://schema.org/Product"> <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="no-js ie8"
                    itemscope itemtype="http://schema.org/Product"> <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="no-js ie9"
                    itemscope itemtype="http://schema.org/Product"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="en" class="no-js"
                    itemscope itemtype="http://schema.org/Product"> <!--<![endif]-->
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

  <!-- Title & Google+ description -->
  
  <title>A Tour of the Dart Language | DartLang.org</title> 
  <meta itemprop="name" content="A Tour of the Dart Language | DartLang.org">
  <meta itemprop="description" content="Learn how to use each major Dart feature. This tour assumes that you already know how to program in another language.">

	<link rel="stylesheet" href="/css/style.css">
	<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
	<link href="/css/dartboard.css" rel="stylesheet" type="text/css">
	
	
	<link rel="alternate" type="application/atom+xml" href="http://news.dartlang.org/feeds/posts/default" title="Atom feed">
    <link href="https://plus.google.com/109866369054280216564" rel="publisher">
	<script src="/js/modernizr.custom.02548.js"></script>
  
  <script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-26406144-4']);
  _gaq.push(['_setDomainName', 'dartlang.org']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

  <script type="text/javascript">
	window.___gcfg = {lang: 'en'};
	(function() 
	{var po = document.createElement("script");
	po.type = "text/javascript"; po.async = true;po.src = "https://apis.google.com/js/plusone.js";
	var s = document.getElementsByTagName("script")[0];
	s.parentNode.insertBefore(po, s);
	})();
  </script>
</head>
<body>
	<div id="container">
		<header>
		  	<div id="plus1"><div class="g-plusone" data-size="standard" data-count="true"></div></div>
      	<a href="/"><img src="/imgs/dart-logo.png" width="268" height="116" alt="Dart"></a>
			  <span id="tagline">Structured web apps</span>
		</header>

		
		<nav>
  <form action="/search.html" id="cse-search-box">
    <div id="search">
      <input type="hidden" name="cx" value="011220921317074318178:i4mscbaxtru" />
      <input type="hidden" name="ie" value="UTF-8" />
      <input type="hidden" name="hl" value="en" />
      <input type="search" name="q" id="q" autocomplete="off" placeholder="Search"/>
    </div>
  </form>

  <ul>
    <li><a href="/downloads.html">Downloads</a></li>
    <li>Getting Started
      <ul>
        <li><a href="/language-tour/">Language Tour</a></li>
        <li><a href="/docs/technical-overview/">Technical Overview</a></li>
        <li><a href="http://synonym.dartlang.org">Translations from JavaScript</a></li>
      </ul> </li>
    <li>Language &amp; Libraries
      <ul>
        <li><a href="/docs/spec/">Language Specification</a></li>
        <li><a href="http://api.dartlang.org/">API Reference</a></li>
      </ul> </li>
    <li>Tools
      <ul>
        <li><a href="http://try.dartlang.org">Dartboard</a></li>
        <li><a href="/docs/getting-started/editor/">Dart Editor</a></li>
        <li><a href="/dartium/">Chromium with the Dart VM</a></li>
        <li><a href="/docs/getting-started/sdk/">SDK</a></li>
      </ul> </li>
    <li>Resources
      <ul>
        <li><a href="/samples/">Code Samples</a></li>
        <li><a href="/articles/">Articles</a></li>
        <li><a href="/support/faq.html">FAQ</a></li>
        <li><a href="/slides/">Presentations</a></li>
        <li><a href="/resources/">More</a></li>
      </ul> </li>
    <li><a href="/support/">Contact Us</a></li>
  </ul>

  <div id="pluspage"><div class="g-plus" data-href="https://plus.google.com/109866369054280216564" data-width="100" data-height="131" data-theme="light"></div></div>
</nav>


		<div id="main" role="main">
			<article>
				<script>
// a bad link got out into wild
if (window.location.hostname != 'www.dartlang.org') {
  window.location = 'http://www.dartlang.org/language-tour/';
}
</script>

<h1> A Tour of the Dart Language </h1>

<section class="overview">
<p>
Welcome to the Dart language tour!
We'll show you how to use each major Dart feature,
from variables to operators to classes and libraries,
with the assumption that you already know how to program in another language.
</p>

<aside class="note">
<b>Tip:</b>
Create a server application project in
<a href="/docs/getting-started/editor/">Dart Editor</a>
so you can play with each feature.
</aside>

<p>
Consult the
<a href="/docs/spec/index.html">Dart Language Specification</a>
whenever you want more details about a language feature.
</p>

<h4> Contents </h4>
<ol class="toc">
  <li> <a href="#main-print">A basic Dart program</a> </li>
  <li> <a href="#variables">Variables</a> </li>
  <li> <a href="#built-in-types">Built-in types</a> </li>
  <li> <a href="#functions">Functions</a> </li>
  <li> <a href="#operators">Operators</a> </li>
  <li> <a href="#control-flow">Control flow</a> </li>
  <li> <a href="#exceptions">Exceptions</a> </li>
  <li> <a href="#classes">Classes</a> </li>
  <li> <a href="#interfaces">Interfaces</a> </li>
  <li> <a href="#generics">Generics</a> </li>
  <li> <a href="#libraries">Libraries and visibility</a> </li>
  <li> <a href="#isolates">Isolates</a> </li>
  <li> <a href="#typedefs">Typedefs</a> </li>
  <li> <a href="#comments">Comments</a> </li>
</ol>

</section>





<section>
<h2 id="main-print"> A basic Dart program </h2>
<p>
Here's some code
that uses some of Dart's most basic features.
</p>




<pre class="prettyprint lang-dart linenums:0 ">main() {
  // variables and values
  int number   = 42;
  String text     = "The value of number is";

  // console output
  print("$text $number.");
}</pre>




<p>
Here's what this program uses
that applies to all (or almost all) Dart apps:
</p>




<dl>
  <dt> main() </dt>
  <dd>
    The special, <b>required</b>,
   top-level function where app execution starts.
  </dd>
  <dt> // </dt>
  <dd>
    How you indicate that the rest of the line is a
    <a href="#comments">comment</a>.
    Alternatively:
    <pre class="prettyprint lang-dart linenums:0 ">/* comment that might span many lines */</pre>
  </dd>
  <dt> int, String </dt>
  <dd>
    Declare a variable with static type annotations.
  </dd>

  <dt> "..." (or '...')</dt>
  <dd>
    A string.
  </dd>

  <dt> $text </dt>
  <dd>
    String interpolation, including a variable's toString() value inside of a string literal.
  </dd>
  <dt> print() </dt>
  <dd>
    A handy way to display output.
  </dd>
</dl>


<h3>Style</h3>

<p>Our code follows the conventions in the
<a href="/articles/style-guide/">Dart Style Guide</a>.
For example,
we indent two spaces by convention.</p>

<h3>Runtime modes</h3>

<p>Dart programs can run in either production mode or checked mode.</p>

<p><em>Production mode</em> is the default runtime mode of a Dart
program, optimized for speed.
In production mode, the optional static types are ignored.</p>

<p><em>Checked mode</em> is a developer friendly mode
that helps you catch some type errors during runtime.
For example, if you assign a non-string to a variable declared as a String,
an exception will be thrown.</p>

<p>We recommend that you develop and debug in checked mode,
and deploy to production mode.</p>

</section>

<section>
  <h2 id="variables"> Variables </h2>
  <p>Here's an example of creating a variable and assigning a value to it:</p>

<pre class="prettyprint lang-dart linenums:0 ">
var name = 'Bob';
</pre>


<p>Variables are references. The variable named <code>name</code> contains a reference
to a String object with a value of "Bob".</p>

<h4>Default value</h4>

<p>Uninitialized variables have an initial value of <code>null</code>. This includes numbers,
which are also objects.</p>

<pre class="prettyprint lang-dart linenums:0 ">
num lineCount;
lineCount == null; // true
</pre>


<h4>Optional types</h4>

<p>You have the option of adding static types to your variable declarations:</p>

<pre class="prettyprint lang-dart linenums:0 ">
String name = 'Bob';
</pre>


<p>Adding types is a good way to clearly express your intent.
Tools like compilers and editors can use these types to
help you, by providing early warnings for bugs and code completion.</p>

<h4>final</h4>

<p>If you never intend to change a variable, use <code>final</code> instead of var or in
addition to a type. Once a <code>final</code> variable is set, it can't be changed.</p>

<pre class="prettyprint lang-dart linenums:0 ">
final String name = 'Bob';
<span class="code-error">name = 'Alice'; // compile ERROR (VM or to JavaScript)</span>
</pre>


<h4>Summary</h4>

<p>Dart variables are optionally typed, though we generally recommend using types.
Variables can be marked as <code>final</code>, locking the value. Unitialized variables
have an initial value of <code>null</code>.</p>

</section>

<section>
<h2 id="built-in-types"> Built-in types </h2>
<p>
The Dart language has special support for the following types:
</p>

<ul>
  <li> <a href="#strings">strings</a> </li>
  <li> <a href="#numbers">numbers</a> </li>
  <li> <a href="#booleans">booleans</a> </li>
  <li> <a href="#lists">lists</a> (also known as <em>arrays</em>) </li>
  <li> <a href="#maps">maps</a> </li>
</ul>

<p>
You can initialize an object of any of these special types
using a <em>literal</em>.
For example, 'this is a string' is a string literal,
and <b>true</b> is a boolean literal.
</p>

<p>
Because every variable in Dart is an object&mdash;an
instance of a <em>class</em>&mdash;you
can usually use <em>constructors</em> to create variables.
Variables for the built-in types are no different.
For example, you can use the Map() constructor to create a map,
using the code <code>new Map()</code>.
</p>

<section>
<h3 id="strings"> Strings </h3>
<p>
A Dart string is a sequence of Unicode character codes.
You can use either single or double quotes
to create a string:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var s1 = 'Single quotes work well for string literals.';
var s2 = "Double quotes work just as well.";
var s3 = 'It\'s easy to escape the string delimiter.';
var s4 = "It's even easier to just use the other string delimiter.";
</pre>

<p>
You can put the value of an expression inside a string
by using ${<em>expression</em>}.
If the expression is a variable,
you can skip the {}.
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var s = 'string interpolation';

print('Dart has $s, which is very handy.');
print('That deserves all caps. ${s.toUpperCase()} is very handy!');
</pre>

<p>
You can concatenate strings using
adjacent string literals:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var s = 'string ''concatenation'
        " works even over line breaks ";
print(s); // string concatenation works even over line breaks
</pre>

<p>
Another way to create a multi-line string:
use a triple quote
with either single or double quotation marks.
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var s1 = '''
You can create
multi-line strings like this one.
''';

var s2 = """This is also a
multi-line string.""";
</pre>



<p>
You can create a "raw" string
by prefixing it with @.
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var s = @'In a raw string, even \n is ignored.';
</pre>



<p>
As for all objects,
you can check whether two strings are equivalent
(have the same characters)
using the <b>==</b> operator:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var name = 'NAME';
var greeting = "Hello, $name!";
var greetingTemplate = 'Hello, NAME!';

print(greeting == greetingTemplate); // true; they have the same characters
</pre>


<section id="strings-string">
<h4> String methods </h4>

<p>
Each string literal has the type
<a href="http://api.dartlang.org/dart_core/String.html">String</a>.
String has some handy methods,
including some that let you determine whether a string
starts with, ends with, or contains another string.
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var fullName = 'Cuthbert Musgrave Girdlestone, III';

fullName.startsWith('Cuthbert');            // true
fullName.endsWith('III');                   // true
fullName.contains(new RegExp('Musgrave'));  // true
</pre>

<p>
Strings are immutable objects,
which means you can create them but you can't change them.
If you look closely at the
<a href="http://api.dartlang.org/dart_core/String.html">String API docs</a>,
you'll notice that none of the methods
actually changes the state of a String.
For example, the method replaceAll() returns a new String
without changing the original String.
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var greetingTemplate = 'Hello, NAME!';
var greeting = greetingTemplate.replaceAll(new RegExp("NAME"), 'Bob');
print(greeting == greetingTemplate); // false; greetingTemplate didn't change
</pre>


<section id="strings-buffer">
<h4> StringBuffer methods </h4>

<p>
To programmatically generate a string, you can use
<a href="http://api.dartlang.org/dart_core/StringBuffer.html">StringBuffer</a>.
A StringBuffer doesn't generate a new String object
until toString() is called.
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var sb = new StringBuffer();

sb.add("Use a StringBuffer");
sb.addAll(["for ", "efficient ", "string ", "creation "]);
sb.add("if you are ").add("building lots of strings.");

var fullString = sb.toString();

print(fullString); // use a StringBuffer for efficient string creation
                   // if you are building lots of strings

sb.clear();        // all gone!
</pre>

<br>
<aside class="note">
<b>Note:</b>
StringBuffers are currently slow when compiled to JavaScript.
See bug #<a href="http://code.google.com/p/dart/issues/detail?id=1216">1216</a>
for details.
</aside>

</section>

</section>

<section>
<h3 id="numbers"> Numbers </h3>
<p>
Dart numbers come in two flavors:
</p>

<dl>
  <dt> <a href="http://api.dartlang.org/dart_core/int.html">int</a> </dt>
  <dd> Integers of arbitrary size </dd>
  <dt> <a href="http://api.dartlang.org/dart_core/double.html">double</a> </dt>
  <dd> Decimal 64-bit doubles, as specified by the IEEE 754 standard </dd>
</dl>

<p>
Both <b>int</b> and <b>double</b> are subinterfaces of
<a href="http://api.dartlang.org/dart_core/num.html"><b>num</b></a>.
The num interface defines basic operators such as +, -, /, and *,
as well as bitwise operators such as &gt;&gt;.

The num interface is also
where you'll find abs(), ceil(), and floor(), among other methods.
If num and its subinterfaces don't have what you're looking for, the
<a href="http://api.dartlang.org/dart_core/Math.html">Math</a> class might.
</p>

<p>
Integers are numbers without a decimal point.
Here are some examples of defining integer literals:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var x = 1;
var hex = 0xDEADBEEF;
var bigInt = 3465346583465243765923847659234765928347659567398475647495873984572947593470294387093493456870849216348723763945678236420938467345762304958724596873045876234572037862934765294365243652548673456705673465273465246734506873456729457623845623456234650457693475603768922346728346256;
</pre>



<p>
If a number includes a decimal,
it is a double.
Here are some examples of defining double literals:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var y = 1.1;
var exponents = 1.42e5;
</pre>

<p>
Here's how you turn a string into a number, or vice versa:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
// string -> int
var one = Math.parseInt("1");                   // 1

// string -> double
var onePointOne = Math.parseDouble("1.1");      // 1.1

// int -> string
String oneAsString = 1.toString();              // "1"

// double -> string
String piAsString = 3.14159.toStringAsFixed(2); // "3.14"
</pre>



</section>

<section>
<h3 id="booleans"> Booleans </h3>
<p>
Dart has a formal boolean type, named <b>bool</b>.
Only two objects have type bool:
the boolean literals, <b>true</b> and <b>false</b>.
</p>

<p>
When Dart expects a boolean value,
if that value isn't <b>true</b>,
then it is <b>false</b>.
Unlike in JavaScript,
values such as 1 or non-null objects are not treated as true.
</p>

<p>
For example, consider the following code:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var name = 'Bob';
if (name) {
  print("You have a name!"); // prints in JavaScript, not in Dart
}
</pre>

<p>
In JavaScript, this code prints "You have a name!" because
<code>name</code> is a non-null object.
However, in Dart, the above doesn't print at all
because <code>name</code> is converted to <b>false</b>
because <code>name != true</code>.
</p>

<p>
Here's another example of code
that behaves differently in JavaScript and Dart:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
if (1) {
  print("JavaScript prints this line because it thinks 1 is true.");
} else {
  print("Dart prints this line because it thinks 1 is NOT true.");
}
</pre>

<br>
<aside class="note">
<b>Note:</b>
Dartboard currently has the wrong behavior for the previous two samples:
it prints the same string that JavaScript would.
(See bug #<a href="http://code.google.com/p/dart/issues/detail?id=1190">1190</a>
for details.)
Also note that,
unlike most of the samples in this tour,
the previous two samples don't work in checked mode.
</aside>

<p>
Dart's treatment of booleans is designed
to avoid the strange behaviors that can arise
when many values can be treated as true.
What this means for you is that,
instead of using code like
<code>if&nbsp;(<em>nonboolean_value</em>)</code>,
you should instead explicitly check for values.
For example:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
// check for an empty string
var fullName = '';
if (fullName.isEmpty()) {
  print("Please enter a full name");
}

// check for zero
var hitPoints = 0;
if (hitPoints == 0) {
  print("Uh oh! Looks like you died.");
}

// check for null
var unicorn = null;
if (unicorn == null) {
  print("You didn't wish hard enough. Wish harder.");
}

// check for NaN
var iMeantToDoThis = 0/0;
if (iMeantToDoThis.isNaN()) {
  print("0/0 is not a number.");
}
</pre>



</section>
</section>

<section>
<h3 id="lists"> Lists (also known as arrays) </h3>
<p>
Perhaps the most common collection in nearly every programming language
is the <em>array</em>, or ordered set of objects.
In Dart, arrays are List objects,
so we usually just call them <em>lists</em>.
When you compile Dart to JavaScript,
a Dart list compiles to a JavaScript array.
</p>

<p>
Dart list literals look like JavaScript array literals.
Here's a simple Dart list:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var list = [1,2,3];
</pre>

<p>
You can get a list's length
and refer to list elements
just as you would in JavaScript:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var list = [1,2,3];
print(list.length); // the # of elements: 3
print(list[1]);     // the second item: 2
</pre>

<p>
You can add an element to a list using the <b>add()</b> method:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var list = [1,2,3];
list.add(4);
</pre>

<p>
To remove elements from a list
(reducing the list's size),
use the <b>removeRange()</b> method:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var list = [1,2,3,4];
list.removeRange(2, 1); // remove the third element
</pre>

<section id="list-iterate">
<h4> Iterating </h4>

<p>
When you need to work on each element of a list,
you can use <b>for</b>, <b>for</b>...<b>in</b>, or <b>forEach()</b>.
Use <b>for</b> when you need the current iteration index:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var list = [1,2,3];
for (var x = 0; x &lt; list.length; x++) {
  print('$x: ${list[x]}');
}
</pre>

<p>
If you don't need the index,
you can use <b>for</b>...<b>in</b>:
</p>



<pre class="prettyprint lang-dart linenums:0 ">
var list = [1,2,3];
for (final x in list) {
  print(x);
}
</pre>

<p>
If you just want to apply a function to each element of the list,
use the <b>forEach()</b> method:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var list = [1,2,3];
void printElement(element) => print(element);
list.forEach(printElement);
</pre>

<p>
Or, more succintly:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var list = [1,2,3];
list.forEach((element) => print(element));
</pre>

</section>


<section id="list-collection">
<h4> List and Collection methods </h4>

<p>
The <a href="http://api.dartlang.org/dart_core/Collection.html#forEach">forEach()</a> method
is just one of many handy methods defined by the
<a href="http://api.dartlang.org/dart_core/List.html">List</a>
interface and its superinterface,
<a href="http://api.dartlang.org/dart_core/Collection.html">Collection</a>.
For example, 
the <a href="http://api.dartlang.org/dart_core/Collection.html#filter">filter()</a> method
returns a new collection with only the elements that satisfy a condition.
The <a href="http://api.dartlang.org/dart_core/Collection.html#every">every()</a> and
<a href="http://api.dartlang.org/dart_core/Collection.html#some">some()</a> methods
check whether a collection matches
every condition or at least one condition, respectively.
The <a href="http://api.dartlang.org/dart_core/List.html#sort">sort()</a> method
lets you sort a list using any criteria you like.
</p>

<p>
For more information about lists,
see <a href="#generics">Generics</a>.
</p>

</section>
</section>

<section>
<h3 id="maps"> Maps </h3>
<p>
In general, a map is an object that associates keys to values.
Dart support for maps is provided by map literals and the
<a href="http://api.dartlang.org/dart_core/Map.html">Map</a> interface.
</p>

<p>
Here's a simple Dart map:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var gifts = {                         // a map literal
// keys       values
  "first"  : "partridge",
  "second" : "turtledoves",
  "fifth"  : "golden rings"};
</pre>

<p>
In map literals, each <b>key</b> must be a string.
If you use a Map constructor,
then you have more options:
the key can be a string, a number, or any other object
that implements the
<a href="http://api.dartlang.org/dart_core/Hashable.html">Hashable</a>
interface.
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var map = new Map();                  // use a Map constructor
map[1] = "partridge";                 // key is 1; value is "partridge"
map[2] = "turtledoves";               // key is 2; value is "turtledoves"
map[5] = "golden rings";              // key is 5; value is "golden rings"
</pre>

<p>
A map <b>value</b> can be any object or null.
</p>

<p>
You add a new key-value pair to an existing map
just as you would in JavaScript:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var gifts = { "first": "partridge" };
<b>gifts["fourth"] = "calling birds";</b>    // add a key-value pair
</pre>

<p>
You retrieve a value from a map the same way you would in JavaScript:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var gifts = { "first": "partridge" };
print(gifts['first']);                // partridge
</pre>

<p>
If you look for a key that isn't in a map,
you get a null in return.
However, because values can be null,
you might need to use a method such as
<a href="http://api.dartlang.org/dart_core/Map.html#containsKey">containsKey()</a> or
<a href="http://api.dartlang.org/dart_core/Map.html#putIfAbsent">putIfAbsent()</a>
to make sure you interpret null correctly.
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var gifts = { "first": "partridge" };
print(gifts['fifth']);                // null
</pre>

<p>
Use <b>.length</b> to get the number of key-value pairs in the map:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var gifts = { "first": "partridge" };
gifts["fourth"] = "calling birds";
print(<b>gifts.length</b>);                  // 2
</pre>

<p>
To remove a key-value pair from a map,
use the <b>remove()</b> method:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var gifts = { "first": "partridge" };
gifts["fourth"] = "calling birds";
<b>gifts.remove('first');</b>
print(gifts.length);                  // 1
print(gifts['first']);                // null
</pre>

<p>
You can copy a map using the <b>Map.from()</b> constructor:
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var gifts = { "first": "partridge" };
var regifts = new Map.from(gifts);
print(regifts['first']);              // partridge
</pre>


<section id="maps-iterating">
<h4> Iterating </h4>

<p>
You have a few choices for iterating through the contents of a map.
Using the <b>forEach()</b> method gives you access to both
the key and the value.
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var gifts = {
  "first" : "partridge",
  "second": "turtledoves",
  "fifth" : "golden rings"};
gifts.forEach((k,v) => print('$k : $v'));
</pre>

<aside class="note">
<b>Note:</b>
Don't depend on forEach() returning
the key-value pairs in a particular order.
</aside>

<p>
If you are interested in just the keys or just the values,
use <b>getKeys()</b> or <b>getValues()</b>, respectively.
Both methods return a
<a href="http://api.dartlang.org/dart_core/Collection.html">Collection</a> object.
</p>

<pre class="prettyprint lang-dart linenums:0 ">
var gifts = {"first": "partridge", "second": "turtledoves"};
var values = gifts.getValues();
values.forEach((v) => print(v));      // partridge, turtledoves
</pre>

<aside class="note">
<b>Note:</b>
Map itself does not extend the Collection interface.
</aside>

</section>

</section>

<section>
<h3 id="builtin-summary"> Summary of built-in types </h3>

<p>
Dart's <a href="#built-in-types">built-in types</a> all
have special literals and implement a built-in interface.
For example, numbers have literals such as
<code>1</code> and
<code>1.1</code>,
and they implement the num interface.
</p>

<p>
You often use literals to create objects of most built-in types,
but you can also use constructors.
Booleans are unusual because you can't create new objects
of type <code>bool</code>;
you're stuck with <code>true</code> and <code>false</code>.
</p>

<p>
For more information about maps and lists,
see <a href="#generics">Generics</a>.
</p>

</section>

</section>

<section>
  <h2 id="functions"> Functions </h2>
  <p>Here's a simple function:</p>

<pre class="prettyprint lang-dart linenums:0 ">
String say(String from, String msg) => "$from says $msg";
</pre>


<p>And here's an example of calling it:</p>

<pre class="prettyprint lang-dart linenums:0 ">
print(say("Bob", "Hello")); // "Bob says Hello"
</pre>


<p>Omitting the types, you could write the above as:</p>

<pre class="prettyprint lang-dart linenums:0 ">
say(from, msg) => "$from says $msg";
</pre>


<p>However, we recommend using types for function signatures.</p>

<p>The <code>=&gt; e;</code> syntax is a shorthand for <code>{ return e; }</code>.
For example, <code>say(from, msg) =&gt; "$from says $msg";</code>
is the same as:</p>

<pre class="prettyprint lang-dart linenums:0 ">
say(from, msg) {
  return "$from says $msg";
}
</pre>


<h4>Optional parameters</h4>

<p>Wrapping a function parameter in <code>[]</code> marks it as an optional parameter.</p>

<pre class="prettyprint lang-dart linenums:0 ">
String say(String from, String msg, [String device]) {
  var result = "$from says $msg";
  if (device != null) {
    result = "$result with a $device";
  }
  return result;
}
</pre>


<p>Here's an example of calling this function without the optional parameter:</p>

<pre class="prettyprint lang-dart linenums:0 ">
print(say("Bob", "Howdy")); // Bob says Howdy
</pre>


<p>Here's an example of calling this function with the third parameter:</p>

<pre class="prettyprint lang-dart linenums:0 ">
print(say("Bob", "Howdy", "smoke signal"));
// Bob says Howdy with a smoke signal
</pre>


<h4>Default values for optional parameters</h4>

<p>Optional parameters may have default values. The default values
must be compile time constants. If no default value is
provided, the value is <code>null</code> (as we saw above).</p>

<pre class="prettyprint lang-dart linenums:0 ">
String say(String from, String msg, [String device='carrier pigeon']) {
  var result = "$from says $msg";
  if (device != null) {
    result = "$result with a $device";
  }
  return result;
}
</pre>


<p>Omitting the optional parameter, you can see how the default value is used:</p>

<pre class="prettyprint lang-dart linenums:0 ">
print(say("Bob", "Howdy")); // Bob says Howdy with a carrier pigeon
</pre>


<h4>Named parameters</h4>

<p>Optional parameters are also named parameters.</p>

<pre class="prettyprint lang-dart linenums:0 ">
print(say("Bob", "Howdy", device: "tin can and string"));
// Bob says Howdy with a tin can and string
</pre>


<h4>First class functions</h4>

<p>You can pass a function as a parameter to another function. For example:</p>

<pre class="prettyprint lang-dart linenums:0 ">
List ages = [1,4,5,7,10,14,21];
List oddAges = ages.filter((i) => i % 2 == 1);
</pre>


<p>Which is the same as:</p>

<pre class="prettyprint lang-dart linenums:0 ">
bool isOdd(num i) => i % 2 == 1;
List ages = [1,4,5,7,10,14,21];
List oddAges = ages.filter(isOdd);
</pre>


<p>You can also assign a function to a variable, such as:</p>

<pre class="prettyprint lang-dart linenums:0 ">
var loudify = (msg) => '!!! ${msg.toUpperCase()} !!!';
print(loudify('hello'));
</pre>


<h4>Lexical closures</h4>

<p>Functions can close over variables defined in surrounding scopes.
The below example shows how <code>makeAdder</code> captures the variable <code>n</code>
and makes it available to the function that <code>makeAdder</code> returns.
Whereever the returned function goes, it remembers <code>n</code>.</p>

<pre class="prettyprint lang-dart linenums:0 ">
Function makeAdder(num n) {
  return (num i) => n + i;
}

main() {
  var add2 = makeAdder(2);
  print(add2(3)); // 5
}
</pre>


<p>(Special thanks to Bob Nystrom for this example.)</p>

<h4>Return values</h4>

<p>All functions return a value. If no return value is specified, the statement <code>return null;</code>
is implicitly appended to the function body.</p>

<h3>Summary of functions</h3>

<p>Dart supports first class functions, with optional parameters, named parameters,
and default values for parameters. Functions may be assigned to variables and
passed as parameters to other functions. Functions also support lexical
closures, which allows access to variables outside its immediate lexical scope.</p>

</section>

<section>
  <h2 id="operators"> Operators </h2>
  <p>Dart does operators.
Not only does it define them,
but it lets you redefine many of them.</p>

<p>The following table shows all of Dart's operators,
in order of precedence.</p>

<table class="operatorTable">
<tr>
<th>Description</th>
<th>Operator</th>
<!-- th Associativity /th -->
</tr>

<tr>
<td>unary postfix</td>
<td class="operatorList"><em>expr</em>++ <em>expr</em>-- () [] .</td>
<!-- td left /td -->
</tr>

<tr>
<td>unary prefix</td>
<td class="operatorList">-<em>expr</em> !<em>expr</em> ~<em>expr</em> ++<em>expr</em> --<em>expr</em></td>
<!-- td right /td -->
</tr>

<tr>
<td>multiplicative</td>
<td class="operatorList">* / % ~/</td>
<!-- td left /td -->
</tr>

<tr>
<td>additive</td>
<td class="operatorList">+ -</td>
<!-- td left /td -->
</tr>

<tr>
<td>shift</td>
<td class="operatorList">&lt;&lt; &gt;&gt;</td>
<!-- td left /td -->
</tr>

<tr>
<td>relational</td>
<td class="operatorList">is is! &gt;= &gt; &lt;= &lt;</td>
<!-- td none /td -->
</tr>

<tr>
<td>equality</td>
<td class="operatorList">== != === !==</td>
<!-- td none /td -->
</tr>

<tr>
<td>bitwise AND</td>
<td class="operatorList">&amp;</td>
<!-- td left /td -->
</tr>

<tr>
<td>bitwise XOR</td>
<td class="operatorList">^</td>
<!-- td left /td -->
</tr>

<tr>
<td>bitwise OR</td>
<td class="operatorList">|</td>
<!-- td left /td -->
</tr>

<tr>
<td>logical AND</td>
<td class="operatorList">&amp;&amp;</td>
<!-- td left /td -->
</tr>

<tr>
<td>logical OR</td>
<td class="operatorList">||</td>
<!-- td left /td -->
</tr>

<tr>
<td>conditional</td>
<td class="operatorList"><em>expr</em> ? <em>expr</em> : <em>expr</em></td>
<!-- td none /td -->
</tr>

<tr>
<td>assignment</td>
<td class="operatorList">= *= /= ~/= %= += -= &lt;&lt;= &gt;&gt;= &amp;= ^= |= </td>
<!-- td right /td -->
</tr>
</table>


<p>For example, the <b>%</b> operator
has higher precedence than
(and thus executes before) the <b>==</b> operator,
which has higher precedence than the <b>&amp;&amp;</b> operator.
That precedence means that
the following two lines of code execute the same way:</p>

<pre class="prettyprint lang-dart linenums:0 ">
if ((n % i == 0) && (d % i == 0)) // parens improve readability
if (n % i == 0 && d % i == 0)     // harder to read, but equivalent
</pre>


<p>This section covers the following topics:</p>

<ul>
  <li> <a href="#op-arithmetic">arithmetic operators</a> </li>
  <li> <a href="#op-equality">equality and relational operators</a> </li>
  <li> <a href="#op-assign">assignment operators</a> </li>
  <li> <a href="#op-logical">logical operators</a> </li>
  <li> <a href="#op-bit">bitwise and shift operators</a> </li>
  <li> <a href="#op-other">other operators</a> </li>
  <li> <a href="#op-methods">operators as methods</a> </li>
</ul>


<p><section id="op-arithmetic"></p>

<h3>Arithmetic operators</h3>

<p>Dart supports the usual arithmetic operators.</p>

<table class="operatorTable">
  <tr> <th> Operator </th> <th> Meaning </th> </tr>
  <tr>
    <td class="operator"> + </td>  <td> add </td>
  </tr><tr>
    <td class="operator"> &ndash; </td>  <td> subtract </td>
  </tr><tr>
    <td class="operator"> -<em>expr</em> </td>
    <td> unary negation (reverse the sign of the expression) </td>
  </tr><tr>
    <td class="operator"> * </td>  <td> multiply </td>
  </tr><tr>
    <td class="operator"> / </td>  <td> divide </td>
  </tr><tr>
    <td class="operator"> ~/ </td> <td> divide, returning an integer result </td>
  </tr><tr>
    <td class="operator"> % </td>  <td> get the remainder </td>
  </tr>
</table>


<p>Example:</p>

<pre class="prettyprint lang-dart linenums:0 ">
int a = 2;
int b = 3;

print('${a + b}');  // 5
print('${a - b}');  // -1
print('${a * b}');  // 6
print('${a / b}');  // 0.6666666666666666
print('${a ~/ b}'); // 0 (quotient)
print('${a % b}');  // 2 (remainder)
</pre>


<p>Dart also supports both prefix and postfix
increment and decrement operators.</p>

<table class="operatorTable">
  <tr> <th> Operator </th> <th> Meaning </th> </tr>
  <tr>
    <td class="operator"> ++<em>var</em> </td>
    <td> <em>var</em> = <em>var</em> + 1
      (expression value is <em>var</em> + 1)</em> </td>
  </tr><tr>
    <td class="operator"> <em>var</em>++ </td>
    <td> <em>var</em> = <em>var</em> + 1
      (expression value is <em>var</em>) </td>
  </tr><tr>
    <td class="operator"> --<em>var</em> </td>
    <td> <em>var</em> = <em>var</em> &ndash; 1
      (expression value is <em>var</em> &ndash; 1) </td>
  </tr><tr>
    <td class="operator"> <em>var</em>-- </td>
    <td> <em>var</em> = <em>var</em> &ndash; 1
      (expression value is <em>var</em>) </td>
  </tr>
</table>


<p>Example:</p>

<pre class="prettyprint lang-dart linenums:0 ">
int a = 2;

print('${ ++a }'); // 3 (increment before returning a value)
print('${ a++ }'); // 3 (increment after returning a value)
print('${ a-- }'); // 4 (decrement after returning a value)
print('${ --a }'); // 2 (decrement before returning a value)
</pre>


<p></section></p>

<p><section id="op-equality"></p>

<h3>Equality and relational operators</h3>

<table class="operatorTable">
  <tr> <th> Operator </th> <th> Meaning </th> </tr>
  <tr>
    <td class="operator"> == </td>
    <td> equal <em>(see discussion below)</em> </td>
    <td>
  </tr><tr>
    <td class="operator"> != </td>
    <td> not equal </td>
  </tr><tr>
    <td class="operator"> === </td>
    <td> same instance </td>
  </tr><tr>
    <td class="operator"> !== </td>
    <td> not the same instance </td>
  </tr><tr>
    <td class="operator"> > </td>
    <td> greater than </td>
  </tr><tr>
    <td class="operator"> &lt; </td>
    <td> less than </td>
  </tr><tr>
    <td class="operator"> >= </td>
    <td> greater than or equal to </td>
  </tr><tr>
    <td class="operator"> &lt;= </td>
    <td> less than or equal to </td>
  </tr><tr>
    <td class="operator"> is </td>
    <td> true if the object has the specified type
      <em>(see discussion below)</em> </td>
  </tr><tr>
    <td class="operator"> is! </td>
    <td> false if the object has the specified type </td>
  </tr>
</table>


<p>To test whether two objects x and y represent the same thing,
use the <strong>==</strong> operator.
You don't usually need to use the <strong>===</strong> operator,
which tests whether two objects are, in fact,
the exact same object.
Here's how the <strong>==</strong> operator will work:</p>

<ol>
<li>If <code>x===y</code>, return true.</li>
<li>Otherwise, if either x or y is null, return false.</li>
<li>Otherwise, return the result of <code>x.equals(y)</code>.</li>
</ol>


<p>The <strong>is</strong> and <strong>is!</strong> operators are handy for checking types.
The result of <code>obj <b>is</b> T</code>
is true if obj implements the interface specified by T.
For example, <code>obj <b>is</b> Object</code> is always true.</p>

<p>Here's an example of using each of the equality and relational operators:</p>

<pre class="prettyprint lang-dart linenums:0 ">
int a = 2;
int b = 3;
int c = a;

print(a == 2);       // true; 2 and 2 are equal
print(a != b);       // true; 2 and 3 aren't equal
print(a === c);      // true; a and c are the same object
print(a !== b);      // true; 2 and 3 aren't the same object
print(b > a);        // true; 3 is more than 2
print(a < b);        // true; 2 is less then 3
print(b >= b);       // true; 3 is greater than or equal to 3
print(a <= b);       // true; 2 is less than or equal to 3
print(a is num);     // true; 2 is a number
print(a is! String); // true; 2 is an int, not a string
</pre>


<p></section></p>

<p><section id="op-assign"></p>

<h3>Assignment operators</h3>

<p>You assign values using the <b>=</b> operator.
You can also use compound assignment operators,
which combine an operation with an assignment.</p>

<table>
  <tr>
    <th> </th>
    <th>Compound assignment</th>
    <th>Equivalent expression</th>
  </tr><tr>
    <th align="left"> For an operator <em>op</em>: </th>
    <td> <code>a <em>op</em>= b</code> </td>
    <td> <code>a = a <em>op</em> b</code> </td>
  </tr>
  <tr>
    <th align="left"> Example: </th>
    <td> <code>a += b</code> </td>
    <td> <code>a = a + b</code> </td>
  </tr>
</table>


<p>Here's a full list of the assignment operators:</p>

<p style="column-count:4; -webkit-column-count:4">
= <br>
+= <br>
&ndash;= <br>
*= <br>
/= <br>
~/= <br>
%= <br>
&lt;&lt;= <br>
>>= <br>
&amp;= <br>
^= <br>
|=
</p>


<p>The following example uses both assignment
and compound assignment operators:</p>

<pre class="prettyprint lang-dart linenums:0 ">
int a = 2;           // assign using =

a *= 3;              // assign and multiply: a = a * 3
print('a *= 3: $a'); // a *= 3: 6
</pre>


<p></section></p>

<p><section id="op-logical"></p>

<h3>Logical operators</h3>

<p>You can invert or combine boolean expressions using the logical operators.</p>

<table class="operatorTable">
  <tr> <th> Operator </th> <th> Meaning </th> </tr>
  <tr>
    <td class="operator"> !<em>expr</em> </td>
    <td> inverts the following expression
      (changes false to true, and vice versa) </td>
  </tr><tr>
    <td class="operator"> || </td>
    <td> logical OR </td>
  </tr><tr>
    <td class="operator"> &amp;&amp; </td>
    <td> logical AND </td>
  </tr>
</table>




<pre class="prettyprint lang-dart linenums:0 ">
if (!done && (col == 0 || col == 3)) {
  // ...do something
}
</pre>


<p></section></p>

<p><section id="op-bit"></p>

<h3>Bitwise and shift operators</h3>

<p>You can manipulate the individual bits of objects in Dart.
Usually, you'd use these operators with integers.</p>

<table class="operatorTable">
  <tr> <th> Operator </th> <th> Meaning </th> </tr>
  <tr>
    <td class="operator"> &amp; </td>
    <td> AND </td>
  </tr><tr>
    <td class="operator"> | </td>
    <td> OR </td>
  </tr><tr>
    <td class="operator"> ^ </td>
    <td> XOR </td>
  </tr><tr>
    <td class="operator"> ~<em>expr</em> </td>
    <td> unary bitwise complement (0s become 1s; 1s become 0s) </td>
  </tr><tr>
    <td class="operator"> &lt;&lt; </td>  <td> shift left </td>
  </tr><tr>
    <td class="operator"> >> </td>  <td> shift right </td>
  <tr>
</table>


<p>Here's an example of using bitwise and shift operators.</p>

<pre class="prettyprint lang-dart linenums:0 ">
int value = 0x22;
int bitmask = 0x0F;

print(value);                                // 34 (0x22)
print(value.toRadixString(16));              // 22
print(value.toRadixString(2));               // 100010
print((value & bitmask).toRadixString(16));  // 2  (AND)
print((value & ~bitmask).toRadixString(16)); // 20 (AND NOT)
print((value | bitmask).toRadixString(16));  // 2f (OR)
print((value ^ bitmask).toRadixString(16));  // 2d (XOR)
print((value &lt;&lt; 4).toRadixString(16));       // 220
print((value >> 4).toRadixString(16));       // 2
</pre>


<p></section></p>

<p><section id="op-other"></p>

<h3>Other operators</h3>

<table class="operatorTable">
  <tr> <th style="text-align:center"> Operator </th> <th> Name </th> <th> Meaning </th> </tr>
  <tr>
    <td class="operator"> () </td>
    <td> function application </td>
    <td> represents a function call </td>
  </tr><tr>
    <td class="operator"> [] </td>
    <td> list access </td>
    <td> refers to the value at the specified index in the list </td>
  </tr><tr>
    <td class="operator"> <em>expr1</em>&nbsp;?&nbsp;<em>expr2</em>&nbsp;:&nbsp;<em>expr3</em> </td>
    <td> conditional </td>
    <td> if <em>expr</em> is true, executes <em>expr</em>;
      otherwise, executes <em>expr</em>
      (technically special syntax, not an operator)
      </td>
  </tr><tr>
    <td class="operator"> . </td>
    <td> member access </td>
    <td> refers to a property of an expression;
      example: <code>foo.bar</code> selects property <code>bar</code>
      from expression <code>foo</code> </td>
  </tr>
</table>


<p></section></p>

<p><section id="op-methods"></p>

<h3>Operators are methods</h3>

<p>Operators are just instance methods with special names.
For example, the expression <code>1 + 2</code>
invokes the + method on 1, with the argument 2&mdash;something
like <code>1.+(2)</code>.
This has a couple of consequences:</p>

<ul>
<li>Dart lets you override many operators.
For example, if you define a Vector class,
you might define a + method to add two vectors.</li>
<li>For operators that work on two operands,
the leftmost operand determines
which version of the operator is used.
For example, if you define a Vector class and a Point class,
<code>aVector + aPoint</code> uses the Vector version of +.
</section></li>
</ul>


<p>The following operators can be overridden:</p>

<p style="column-count:4; -webkit-column-count:4">
&lt; <br>
> <br>
&lt;= <br>
>= <br>
&ndash; <br>
+ <br>
/ <br>
~/ <br>
* <br>
% <br>
| <br>
^ <br>
& <br>
&lt;&lt; <br>
>> <br>
[] <!-- (list access operator) --> <br>
[]= <em>(list assignment)</em> <br>
~ <br>

equals() <em>(</em><code>==</code><em>)</em> <!-- (==) --> *

</p>


<p><aside class="note"></p>

<p>* The <strong>==</strong> operator can currently be overridden,
but not for long.
Soon the way to customize the behavior of <strong>==</strong>
will be by overriding the <strong>equals()</strong> method.
</aside></p>

<p>For an example of overriding operators,
see <a href="#classes-operators">Operators</a> in the Classes section.</p>

<p></section></p>

<p><section id="op-summary"></p>

<h3>Summary of operators</h3>

<p>Dart operators should look and act familiar.
Behind the scenes, an operator is a specially named method
that's invoked on its first operand.
As a result, operand order can make a difference:
a+b might not give the same result as b+a.
You can override many operators.
</section></p>

</section>

<section>
  <h2 id="control-flow"> Control flow </h2>
  <p>You can control the flow of your Dart code using any of the following:</p>

<ul>
<li><a href="#if-else">If and else</a></li>
<li><a href="#for-loops">For loops</a></li>
<li><a href="#while">While and do while</a></li>
<li><a href="#break">Break and continue</a></li>
<li><a href="#switch">Switch and case</a></li>
</ul>


<h4 id="if-else">If and else</h4>




<pre class="prettyprint lang-dart linenums:0 ">
if (isRaining()) {
  you.bringRainCoat();
} else if (isSnowing()) {
  you.wearJacket();
} else {
  car.putTopDown();
}
</pre>


<p>Remember, unlike JavaScript, Dart treats all values
that are not <code>true</code> as <code>false</code>.
See <a href="#booleans">Booleans</a> for more info.</p>

<h4 id="for-loops">For loops</h4>


<p>You can iterate with the standard <code>for</code> loop.</p>

<pre class="prettyprint lang-dart linenums:0 ">
for (int i = 0; i < candidates.length; i++) {
  candidates[i].interview();
}
</pre>


<p>Closures inside of Dart's <code>for</code> loops correctly capture the
value of the index, avoiding a common pitfall found in JavaScript.
For example, consider:</p>

<pre class="prettyprint lang-dart linenums:0 ">
main() {
  var callbacks = [];
  for (var i = 0; i < 2; i++) {
    callbacks.add(() => print(i));
  }
  callbacks.forEach((c) => c());
}
</pre>


<p>The output is <code>0</code> and then <code>1</code>, as expected. In contrast,
the example would print <code>2</code> and then <code>2</code> in JavaScript.</p>

<p>If the object that you are iterating over is a <code>Collection</code>,
you can use the <a href="http://api.dartlang.org/dart_core/Collection.html#forEach">forEach()</a>
method. Using forEach() is
a good option if you don't need to know the current iteration
counter.</p>

<pre class="prettyprint lang-dart linenums:0 ">
candidates.forEach((candidate) => candidate.interview());
</pre>


<p>Collections also support the <code>for-in</code> form of iteration:</p>

<pre class="prettyprint lang-dart linenums:0 ">
var collection = [0, 1, 2];
for (var x in collection) {
  print(x);
}
// prints:
// 0
// 1
// 2
</pre>




<h4 id="while">While and do while</h4>


<p>A <code>while</code> loop evaluates the conditional before the loop.</p>

<pre class="prettyprint lang-dart linenums:0 ">
while (!auctionItem.currentWinner(bidder) &&
       auctionItem.currentBid < bidder.maximumBid) {
  auctionItem.placeBid(bidder, auction.currentBid + 1);
}
</pre>


<p>A do while loop evaluates the conditional <em>after</em> the loop.</p>

<pre class="prettyprint lang-dart linenums:0 ">
do {
  printLine();
} while (!atEndOfPage());
</pre>




<h4 id="break">Break and continue</h4>


<p>Use <code>break</code> to stop looping.</p>

<pre class="prettyprint lang-dart linenums:0 ">
while (true) {
  if (shutDownRequested()) break;
  processIncomingRequests();
}
</pre>


<p>Use <code>continue</code> to skip to the next loop iteration.</p>

<pre class="prettyprint lang-dart linenums:0 ">
for (int i = 0; i < candidates.length; i++) {
  var candidate = candidates[i];
  if (candidate.yearsExperience < 5) {
    continue;
  }
  candidate.interview();
}
</pre>


<p>You might write that example differently if you're
using a <a href="http://api.dartlang.org/dart_core/Collection.html">Collection</a>.</p>

<pre class="prettyprint lang-dart linenums:0 ">
candidates.filter((c) => c.yearsExperience >= 5)
          .forEach((c) => c.interview());
</pre>




<h4 id="switch">Switch and case</h4>


<p>Switch statements in Dart compare objects using <code>==</code>. Remember to include a <code>break</code> statement
at the end of each non-empty <code>case</code> clause to avoid fall-through (which is an error, see below).
A <code>default</code> clause can be used to catch conditions that don't match.</p>

<pre class="prettyprint lang-dart linenums:0 ">
var command = 'OPEN';
switch (command) {
  case 'CLOSED':
    executeClose();
    break;
  case 'PENDING':
    executePending();
    break;
  case 'APPROVED':
    executeApproved();
    break;
  case 'DENIED':
    executeDenied();
    break;
  case 'OPEN':
    executeOpen();
    break;
  default:
    executeUnknown();
}
</pre>


<p>The following example omits the <code>break</code> statement in the <code>case</code> clause,
thus generating an error:</p>

<pre class="prettyprint lang-dart linenums:0 ">
var command = 'OPEN';
switch (command) {

  case 'OPEN':
    executeOpen();
    // ERROR: missing break causes an exception to be thrown!!

  case 'CLOSED':
    executeClose();
    break;
}
</pre>


<p>However, Dart does support empty <code>case</code> clauses, allowing a form
of fall-through.</p>

<pre class="prettyprint lang-dart linenums:0 ">
var command = 'CLOSED';
switch (command) {
  case 'CLOSED':     // empty case falls through
  case 'NOW_CLOSED':
    // runs for both CLOSED and NOW_CLOSED
    executeClose();
    break;
}
</pre>


</section>

<section>
  <h2 id="exceptions">Exceptions</h2>
  <p>Your Dart code can throw and catch exceptions. Exceptions are errors that
signal something happened that was not anticipated. If not caught,
exceptions bubble up to the top of the program.</p>

<p>In contrast to Java, all of Dart's exceptions are unchecked exceptions.
Methods do not declare which exceptions they might throw, and
you are not required to catch any exceptions.</p>

<p>Dart provides
an <a href="http://api.dartlang.org/dart_core/Exception.html">Exception</a> interface and numerous predefined exception types.
You can, of course, define your own exceptions by extending the Exception interface.
Some examples of common exceptions include:</p>

<ul>
<li><a href="http://api.dartlang.org/dart_core/IndexOutOfRangeException.html">IndexOutOfRangeException</a></li>
<li><a href="http://api.dartlang.org/dart_core/NoSuchMethodException.html">NoSuchMethodException</a></li>
<li><a href="http://api.dartlang.org/dart_core/NullPointerException.html">NullPointerException</a></li>
<li><a href="http://api.dartlang.org/dart_core/IllegalArgumentException.html">IllegalArgumentException</a></li>
</ul>


<p>However, Dart programs can throw any object as an exception.</p>

<h4>Throw</h4>

<p>Here's how you throw, or <em>raise</em>, an exception.</p>

<pre class="prettyprint lang-dart linenums:0 ">
throw new IllegalArgumentException('Value must be greater than zero');
</pre>


<p>You can also throw arbitrary objects.</p>

<pre class="prettyprint lang-dart linenums:0 ">
throw "Out of llamas!";
</pre>


<h4>Catch</h4>

<p>Catching, or capturing, an exception stops the exception from propagated.
Catching an exception gives you a chance to handle it.</p>

<pre class="prettyprint lang-dart linenums:0 ">
try {
  breedMoreLlamas();
} catch (final OutOfLlamasException e) {
  buyMoreLlamas();
}
</pre>


<p>To handle code that can throw more than one type of exception, you can specify
multiple catch clauses.
The first catch clause that matches the thrown object's
type handles the exception. If the catch
clause does not specify a type, that clause can handle any type of thrown object.</p>

<pre class="prettyprint lang-dart linenums:0 ">
try {
  breedMoreLlamas();
} catch (final OutOfLlamasException e) {  // a specific exception
  buyMoreLlamas();
} catch (final Exception e) {             // anything that is an exception
  print("Unknown exception: $e");
} catch (final e) {                       // no specified type, handles all
  print("Something really unknown: $e");
}
</pre>


<h4>Finally</h4>

<p>To ensure that some code runs whether or not an exception is thrown,
use the finally clause.</p>

<p>If no catch clause matches the exception,
the finally clause runs and then the exception is propagated.</p>

<pre class="prettyprint lang-dart linenums:0 ">
try {
  breedMoreLlamas();
} finally {
  cleanLlamaStalls();  // always run, even if exception is thrown
}
</pre>


<p>The finally clause runs after any matching catch clauses.</p>

<pre class="prettyprint lang-dart linenums:0 ">
try {
  breedMoreLlamas();
} catch (final e) {
  print("Error: $e");  // handle exception first
} finally {
  cleanLlamaStalls();  // then run finally
}
</pre>


</section>

<section>
  <h2 id="classes">Classes</h2>
  <p>Dart is an object-oriented language with classes
and single inheritance. The root class is
<a href="http://api.dartlang.org/dart_core/Object.html">Object</a>.</p>

<h3>Instance variables</h3>

<p>Here's how you declare
a class with instance variables
(also known as member variables):</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Point {
  num x, y;
}
</pre>


<p>All uninitialized instance variables have the value <code>null</code>.</p>

<p>Both final and non-final instance variables generate
an implicit getter method. Non-final instance variables
generate an implicit setter method.
(<a href="#classes-getters-and-setters">Getters and setters</a> are discussed more later.)</p>

<pre class="prettyprint lang-dart linenums:0 ">
main() {
  var point = new Point();

  // use the setter method for x
  point.x = 4;

  // use the getter method for x
  print(point.x);  // 4

  // values default to null
  print(point.y);  // null
}
</pre>


<h4>Instance variable initialization</h4>

<p>If you initialize an instance variable
where it is declared
(instead of in a constructor or method),
the initial value must be a compile-time constant.</p>

<p><aside class="note">
<strong>Note:</strong> This restriction is currently under review.
</aside></p>

<p>An example of a compile-time constant is a number literal:</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Point {
  num x = 0,
      y = 0;
}
</pre>


<p>Use the constructor body, demonstrated in the next section,
to assign non-constant values to instance variables.</p>

<h3>Constructors</h3>

<p>Declare a constructor by creating a method with the
same name as its class. The most common form of constructor,
the generative constructor,
creates a new instance of a class.</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Point {
  num x, y;

  Point(num x, num y) {
    // there's a better way to do this, stay tuned
    this.x = x;
    this.y = y;
  }
}
</pre>


<p>The <code>this</code> keyword references the current instance.</p>

<p><aside class="note">
<strong>Note:</strong> Use <code>this</code> only when there is a name
conflict. Otherwise, Dart style omits the <code>this</code>.
</aside></p>

<p>The pattern of assigning a constructor argument to
a member variable is so common, Dart has syntactic sugar
to make it easy.</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Point {
  num x, y;

  // syntactic sugar for this.x = x and this.y = y
  Point(this.x, this.y);
}
</pre>


<h4>Default constructors</h4>

<p>If you don't declare a constructor,
a default constructor is provided for you.
The default constructor has no arguments and invokes the
the no-argument constructor in the superclass.</p>

<h4>Initializer list</h4>

<p>Final variables must be initialized before the object is assigned to <code>this</code>.
Use the initializer list, which runs before the constructor body,
to initialize any final variables.</p>

<pre class="prettyprint lang-dart linenums:0 ">
#import('dart:html');

class Button {
  final Collection<ButtonHandler> handlers;
  final String domId;
  final Element elem;
  
                // what follows the : is the initializer list
  Button(domId) : domId = domId,
                  handlers = [],
                  elem = document.query(domId) {
    bindHandlers();
  }

  bindHandlers() {
   // ...
  }
}
</pre>


<p>The right-hand side of an initializer does not have access
to <code>this</code>.</p>

<h4>Named constructors</h4>

<p>Use a named constructor to implement multiple
constructors for a class or to provide extra clarity.</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Point {
  num x, y;

  // named constructor
  Point.fromJson(Map json) : x = json['x'], y = json['y'];

  Point(this.x, this.y);
}
</pre>


<p>Create new instances from a named constructor with <code>new</code>:</p>

<pre class="prettyprint lang-dart linenums:0 ">
var jsonData = JSON.parse('{"x":1, "y":2}');
var point = new Point.fromJson(jsonData);
</pre>


<h4>Constant constructors</h4>

<p>Dart has deterministic object creation,
thus avoiding tricky situations found in other languages.
To achieve this, only immutable
compile-time expressions are allowed
for the initial values of instance variable declarations.</p>

<p>An immutable compile-time constant object is known as a <code>const</code> object.
Creating a <code>const</code> object requires defining a <code>const</code>
constructor and ensuring all instance fields are <code>final</code>.</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Point {
  final num x, y;
  const Point(this.x, this.y);
  static final Point origin = const Point(0, 0);
}
</pre>


<p>Because compile-time constants are constant and immutable,
constructing two identitical <code>const</code> objects results in
a single, canonical instance.</p>

<pre class="prettyprint lang-dart linenums:0 ">
void main() {
  var a = const Point(1, 1);
  var b = const Point(1, 1);

  print(a === b); // true, they are the same instance!
}
</pre>


<p><aside class="note">
<strong>Note:</strong> Other examples of compile-time
constants are literal numbers and literal strings.
</aside></p>

<h4>Factory constructors</h4>

<p>Use the <code>factory</code> keyword
when implementing a constructor that
doesn't always create a new instance of its class.
For example, a factory constructor
might return an instance from a cache,
or it might return an instance of a subclass.</p>

<p>The following example demonstrates a factory constructor
returning objects from a cache.</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Logger {
  final String name;
  bool mute = false;

  static Map<String, Logger> _cache;

  factory Logger(String name) {
    if (_cache == null) {
      _cache = {};
    }

    if (_cache.containsKey(name)) {
      return _cache[name];
    } else {
      final logger = new Logger._internal(name);
      _cache[name] = logger;
      return logger;
    }
  }

  Logger._internal(this.name);

  log(String msg) {
    if (!mute) {
      print(msg);
    }
  }
}
</pre>


<p>As for other constructors,
to invoke a factory constructor you use the <code>new</code> keyword:</p>

<pre class="prettyprint lang-dart linenums:0 ">
var logger = new Logger('UI');
logger.log('Button clicked');
</pre>


<p><aside class="note">
<strong>Note:</strong> Factory constructors have no access to <code>this</code>.
</aside></p>

<h3>Methods</h3>

<p>Methods are functions that
provide behavior for an object.</p>

<h4>Instance methods</h4>

<p>Instance methods on objects can access instance variables and <code>this</code>.
The distanceTo() method in the following sample is an
example of an instance method.</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Point {
  num x, y;
  Point(this.x, this.y);

  num distanceTo(Point other) {
    return Math.sqrt(((x-other.x)*(x-other.x)) + ((y-other.y)*(y-other.y)));
  }
}
</pre>


<p>Here's how you invoke the distanceTo() method on
an instance of Point:</p>

<pre class="prettyprint lang-dart linenums:0 ">
var point = new Point(2, 2);
num distance = point.distanceTo(new Point(4,4));
print(distance);  // 2.82842...
</pre>


<p><section id="classes-getters-and-setters"></p>

<h4>Getters and setters</h4>

<p>Getter and setter methods provide read and write access
to internal object state. When calling a getter
or setter, omit the trailing parentheses.
Define getters and setters using the <code>get</code> and <code>set</code>
keywords.</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Rectangle {
  num left, top, width, height;

  Rectangle(this.left, this.top, this.width, this.height);

  num get right()           => left + width;
      set right(num value)  => left = value - width;
  num get bottom()          => top + height;
      set bottom(num value) => top = value - height;
}
</pre>


<p>Use explicit getters and setters just like you
would use the generated getters and setters from
instance variables.</p>

<pre class="prettyprint lang-dart linenums:0 ">
var rect = new Rectangle(3, 4, 20, 15);
print(rect.left); // 3
rect.right = 12;
print(rect.left); // -8
</pre>


<p>With getters and setters, you can start
with instance variables,
later wrapping them with methods,
all without changing client code.</p>

<p><section id="classes-operators"></p>

<h4>Operators</h4>

<p>Because operators are just instance methods with special names,
you can override <a href="#op-methods">many operators</a>.
Here's an example of a class that overrides the <code>+</code> and <code>-</code> operators.</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Vector {
  final int x,y;
  const Vector(this.x, this.y);

  Vector operator +(Vector v) { // overrides + (a + b)
    return new Vector(x + v.x, y + v.y);
  }
  
  Vector operator -(Vector v) { // overrides - (a - b)
    return new Vector(x - v.x, y - v.y);
  }
  
  Vector operator negate() {    // overrides unary negation (-a)
    return new Vector(-x,-y);
  }
  
  String toString() => '($x,$y)';
}

main() {
  Vector v = new Vector(2,3);
  Vector w = new Vector(2,2);
  print(v);   // (2,3)
  print(-v);  // (-2,-3)
  print(v+w); // (4,5)
  print(v-w); // (0,1)
}</pre>


<p><aside class="note">
<strong>Implementation note:</strong>
Overriding <code>-</code> affects only the binary subtraction operator.
To override the unary form of <code>-</code>,
you must use the special identifier <strong>negate</strong>.
</aside></p>

<p></section>
</section></p>

<h3>Abstract classes</h3>

<p>Dart will support abstract classes and abstract methods.</p>

<p>As of 2012-04-04, abstract is not yet implemented. Follow
bugs <a href="http://code.google.com/p/dart/issues/detail?id=1603">1603</a>
and <a href="http://code.google.com/p/dart/issues/detail?id=1605">1605</a>
to track the progress.</p>

<h3>Extending a class</h3>

<p>Use <code>extends</code> to create a subclass, and <code>super</code> to
refer to the superclass.</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Television {
  turnOn() {
    _illuminateDisplay();
    _activeIrSensor();
  }
}

class SmartTelevision extends Television {
  turnOn() {
    super.turnOn();
    _bootNetworkInterface();
    _initializeMemory();
    _upgradeApps();
  }
}
</pre>


<p>Subclasses can override instance methods, getters, and setters.</p>

<h3>Class-level static members</h3>

<p>Use the <code>static</code> keyword to implement class-wide variables and methods.</p>

<h4>Static methods</h4>

<p>Static methods (class methods) do not operate on an instance, and thus
do not have access to <code>this</code>.</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Point {
  num x, y;
  Point(this.x, this.y);

  static num distanceBetween(Point a, Point b) {
    return Math.sqrt(((a.x-b.x)*(a.x-b.x)) + ((a.y-b.y)*(a.y-b.y)));
  }
}

main() {
  var a = new Point(2, 2);
  var b = new Point(4, 4);
  print(Point.distanceBetween(a, b));  // 2.82842...
}
</pre>


<p><aside class="note">
  <strong>Best practice:</strong> Consider using top-level functions,
  instead of static methods, for common or widely
  used utilities and functionality.
</aside></p>

<h4>Static variables</h4>

<p>Static variables (class variables) are useful for class-wide state and
constants.</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Color {
  static final RED = const Color('red');
  final String name;
  const Color(this.name);
  String toString() => name;
}

main() {
  print(Color.RED); // 'red'
}
</pre>


</section>

<section>
  <h2 id="interfaces">Interfaces</h2>
  <p>Interfaces are types that define how you can interact with an object.
An interface can specify methods,
constructors,
instance variables
(or, more precisely, getters and setters),
and superinterfaces.
It doesn't, however, specify the code <em>inside</em> of
methods and constructors.</p>

<p>Interfaces are handy for specifying APIs
without specifying exactly how the APIs are implemented.</p>

<p><section id="interfaces-defining"></p>

<h3>Defining an interface</h3>

<p>Use the <code>interface</code> keyword to define an interface.
For example, here's the code that defines the
<a href="http://api.dartlang.org/dart_core/Hashable.html">Hashable</a> interface:</p>

<pre class="prettyprint lang-dart linenums:0 ">
interface Hashable {
  int hashCode();
}
</pre>


<p>Notice how, instead of having a method body (<code>{...}</code>),
the interface just has a semicolon (<code>;</code>).
</section></p>

<p><section id="interfaces-implementing"></p>

<h3>Implementing an interface</h3>

<p>A class can implement one or more interfaces
by declaring them in its <strong>implements</strong> clause
and then providing the APIs required by the interfaces.
For example:</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Point <b>implements Hashable</b> {
  num x, y;
  ...
  // required by Hashable
  <b>int hashCode() {</b>
    int result = 17;
    result = 37 * result + x.hashCode();
    result = 37 * result + y.hashCode();
    return result;
  <b>}</b>
  ...
}
</pre>


<p>Here's an example of
specifying that a class implements multiple interfaces:</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Point <b>implements Comparable, Hashable</b> {
  ...
}
</pre>


<p><aside class="note">
  <strong>Note:</strong>
  Soon you'll be able to treat Dart classes as interfaces.
  This feature will be useful when creating mock objects for testing.
</aside></p>

<p></section></p>

<p><section id="interfaces-extending"></p>

<h3>Extending an interface</h3>

<p>You can create an interface
that builds on one or more interfaces.
The new interface is called a <em>subinterface</em>,
and all the interfaces it inherits from are its <em>superinterfaces</em>.</p>

<p>Use the <strong>extends</strong> keyword
to specify which interface (or interfaces) you're adding to.
Here's an example of creating a subinterface of Hashable:</p>

<pre class="prettyprint lang-dart linenums:0 ">
interface HashablePoint extends Hashable {
  num x, y;
}
</pre>


<p><aside class="note">
  <strong>Note:</strong>
  Technically, interfaces don't have instance variables
  such as <code>x</code> and <code>y</code>.
  What looks like an instance variable is really a
  shortcut for declaring
  <a href="#classes-getters-and-setters">getter and setter methods</a>.
</aside></p>

<p>Here's an example of implementing a subinterface
and checking types.</p>

<pre class="prettyprint lang-dart linenums:0 ">
class Point implements HashablePoint {
  num x, y; // required by HashablePoint

  // required by Hashable
  int hashCode() {
    ...
  }
}

void main() {
  Point p = new Point();
  print(p is Point);          // true
  print(p is Hashable);       // true
  print(p is HashablePoint);  // true
}
</pre>


<p></section></p>

<p><section id="interfaces-default-class"></p>

<h3>Defining constructors and a default class</h3>

<p>An interface can define constructors,
as long as it specifies a <em>default class</em>.</p>

<p><aside class="note">
  <strong>Note:</strong>
  Many of the Dart APIs are implemented as
  interfaces that have default classes.
  For example, all of the <a href="#built-in-types">built-in types</a>,
  including <a href="#numbers">num and int</a>, are interfaces.
</aside></p>

<p>Use the <code>default</code> keyword to specify
the default class.
For example:</p>

<pre class="prettyprint lang-dart linenums:0 ">
interface ObjectCache default MemoryCache {
  ObjectCache();
  ...
}
</pre>


<p>The code for the default class might look like this:</p>

<pre class="prettyprint lang-dart linenums:0 ">
class MemoryCache implements ObjectCache {
  ...
}
</pre>


<p>Invoking a constructor via an interface
results in a call to the equivalent constructor
in the interface's default class.
For example:</p>

<pre class="prettyprint lang-dart linenums:0 ">
var cache = new ObjectCache(); // same as: new MemoryCache()
</pre>


<p></section></p>

<p><section id="interfaces-summary"></p>

<h3>Summary of interfaces</h3>

<p>Interfaces are everywhere in Dart,
from built-in types to
many of the types defined in the standard Dart libraries.
Because Dart interfaces can have default classes,
you can use interface constructors.
</section></p>

</section>

<section>
  <h2 id="generics">Generics</h2>
  <p>If you look at the API documentation for the basic array type,
<a href="http://api.dartlang.org/dart_core/List.html">List</a>,
you'll see that the type is actually <strong>List&lt;E></strong>.
The &lt;...> notation marks List as a <em>generic</em>
(or <em>parameterized</em>) type&mdash;a
type that can declare formal type parameters.</p>

<h3>Why use generics?</h3>

<p>Because types are optional in Dart,
you never <em>have</em> to use generics.
You might <em>want</em> to, though,
for the same reason you might want to use other types in your code:
Types (generic or not) let you document and annotate your code,
making it easier to express your intent.</p>

<p>For example,
if you intend for a list to contain only strings,
you can declare it as <strong>List&lt;String></strong>
(read that as "List of String").
That way you, your fellow programmers, and your tools
(such as Dart Editor and the Dart VM in checked mode)
can detect that assigning a non-string to the list
is probably a mistake.</p>

<pre class="prettyprint lang-dart linenums:0 ">
List&lt;String> names = new List&lt;String>();
names.addAll(['Seth', 'Kathy', 'Lars']);
...
names.add(42); // fails in checked mode (succeeds in production mode)
</pre>


<p>Another reason for using generics
is to reduce code duplication.
Generics let you share a single interface
and implementation between many types,
while still taking advantage of checked mode
and static analysis early warnings.
For example,
say you create an interface for caching an object:</p>

<pre class="prettyprint lang-dart linenums:0 ">
interface ObjectCache {
  Object getByKey(String key);
  setByKey(String key, Object value);
}
</pre>


<p>You discover that you want a string-specific version of this interface,
so you create another interface:</p>

<pre class="prettyprint lang-dart linenums:0 ">
interface StringCache {
  String getByKey(String key);
  setByKey(String key, String value);
}
</pre>


<p>Later, you decide you want a number-specific version of this interface...
You get the idea.</p>

<p>Generic types can save you the trouble of creating all these interfaces.
Instead, you can create a single interface that takes a type parameter:</p>

<pre class="prettyprint lang-dart linenums:0 ">
interface Cache&lt;T> {
  T getByKey(String key);
  setByKey(String key, T value);
}
</pre>


<p>In this code, T is the stand-in type.
It's a placeholder that you can think of as
a type that a developer will define later.</p>

<p><section id="generics-literals"></p>

<h3>Using collection literals</h3>

<p>Both built-in collection types are parameterized:
<a href="#lists">lists</a> and
<a href="#maps">maps</a>.
Parameterized literals are just like the literals you've already seen,
except that you add <strong>&lt;<em>type</em>></strong>
before the opening bracket.
For example:</p>

<pre class="prettyprint lang-dart linenums:0 ">
List&lt;String> names = <b>&lt;String></b>['Seth', 'Kathy', 'Lars'];
Map&lt;String, String> pages = <b>&lt;String></b>{ // specify <b>value</b> type: String
    'index.html':'Homepage',  // (the <b>key</b> type is implicitly String)
    'robots.txt':'Hints for web robots',
    'humans.txt':'We are people, not machines' };
</pre>


<p><aside class="note">
  <strong>Note:</strong>
  Map literals always have string <em>keys</em>.
  The type before the brace specifies the type of the map's <em>values</em>.
</aside></p>

<p></section></p>

<p><section id="generics-constructors"></p>

<h3>Using constructors</h3>

<p>To specify one or more types when using a constructor,
put the types in angle brackets
(<code>&lt;...></code>)
just after the class or interface name.
For example:</p>

<pre class="prettyprint lang-dart linenums:0 ">
List&lt;String> names = new List<b>&lt;String></b>();
names.addAll(['Seth', 'Kathy', 'Lars']);
Set&lt;String> nameSet = new Set<b>&lt;String></b>.from(names);
</pre>


<p>The following code creates a map
that has integer keys and values of type View:</p>

<pre class="prettyprint lang-dart linenums:0 ">
Map&lt;int, View> views = new Map<b>&lt;int, View></b>();
</pre>


<p></section></p>

<p><section id="generics-collections"></p>

<h3>Generic collections and the types they contain</h3>

<p>Dart generic types are <em>reified</em>,
which is a fancy way of saying that
they carry their type information around at runtime.
For example, you can test the type of a collection,
even in production mode:</p>

<pre class="prettyprint lang-dart linenums:0 ">
List&lt;String> names = new List&lt;String>();
names.addAll(['Seth', 'Kathy', 'Lars']);
print(names is List&lt;String>);           // true
</pre>


<p>However, the <strong>is</strong> expression
checks the type of the <em>collection</em> only&mdash;not
of the objects inside it.
In production mode,
a List&lt;String> might have some non-string items in it.
The solution is to either
check each item's type or
wrap item-manipulation code in an <a href="#exceptions">exception handler</a>.</p>

<p><aside class="note">
  <strong>Note:</strong>
  In contrast,
  generics in Java use <em>erasure</em>,
  which means that generic type parameters are removed at runtime.
  In Java, you can test whether an object is a List,
  but you can't test whether it's a List&lt;String>.
</aside>
</section></p>

<p><section id="generics-summary"></p>

<h3>Summary of generics</h3>

<p>For more information about generics, see
<a href="http://www.dartlang.org/articles/optional-types/">Optional Types in Dart</a>.
</section></p>

</section>

<section>
  <h2 id="libraries">Libraries and visibility</h2>
  <p>This section explains how to use
<a href="#libraries-import">import</a> (<strong>#import</strong>),
<a href="#libraries-source">include</a> (<strong>#source</strong>),
and <a href="#libraries-library">library</a> (<strong>#library</strong>)
directives,
which can help you
create a modular and shareable code base.
Libraries not only provide APIs,
but are a unit of privacy:
they can hide implementation details such as private variables.</p>

<p><b>Every Dart app is a library</b>,
even if it doesn't use #library.</p>

<p><aside class="note">
<b>Note:</b>
The library system in Dart <b>will change</b>.
This section describes how it currently works.
</aside></p>

<p><section id="libraries-import"></p>

<h3>Using libraries</h3>

<p>Use <strong>#import</strong> to
specify how a namespace from one library
is used in the scope of another library.</p>

<p>Dart web apps generally use the
<a href="http://api.dartlang.org/html.html">dart:html</a>
library, which they import like this:</p>

<pre class="prettyprint lang-dart linenums:0 ">
#import('dart:html');
</pre>


<p>The only required argument to #import
is a URI specifying the library.
For built-in libraries,
the URI has the special <code>dart:</code> prefix.
For other libraries,
the URI can be relative to the current directory.
(In the future,
you'll be able to specify a file on a web server.)
For example:</p>

<pre class="prettyprint lang-dart linenums:0 ">
#import('dart:io');
#import('mylib/mylib.dart');
#import('../../util/utilslib.dart');
</pre>


<p><section id="libraries-prefix"></p>

<h4>Specifying prefixes</h4>

<p>If you import two libraries that have conflicting identifiers,
then you can specify a prefix for one or both libraries.
For example, if library1 and library2 both define Element,
then you might have code like this:</p>

<pre class="prettyprint lang-dart linenums:0 ">
#import('lib1/library1.dart');
#import('lib2/library2.dart', prefix:'lib2');
...
var element1 = new Element();      // uses Element from library1
var element2 = new lib2.Element(); // uses Element from library2
</pre>


<p></section>
</section></p>

<p><section id="libraries-library"></p>

<h3>Implementing libraries</h3>

<p>Use <a href="#libraries-source">#source</a>
(also known as an <em>include directive</em>)
to specify the files that
are part of the current library,
and <a href="#libraries-library">#library</a>
to specify that a file
implements a library.</p>

<p><section id="libraries-source"></p>

<h4>Associating a file with the current library</h4>

<p>You can put your library's implementation into multiple .dart files
by using <strong>#source</strong> in the library's main .dart file.</p>

<p><aside class="note">
<strong>Included files can't have directives.</strong>
A single file in each library
must have all the directives (such as #import and #library)
that the library needs.
</aside></p>

<p>For example, consider the following code:</p>

<pre class="prettyprint lang-dart linenums:0 ">
<em>// in Ballgame.dart:</em>
#import('dart:html');

#source('Ball.dart');
#source('Util.dart');
...
main() {
  ...
}
</pre>


<p>In this example, Ball.dart and Util.dart are compiled into
the library Ballgame.dart.
Ballgame.dart doesn't have a #library statement,
but remember that each Dart app has an implicit library.</p>

<p><section id="libraries-library"></p>

<h4>Declaring a library</h4>

<p>To explicitly declare a library, you use a <strong>#library</strong> statement.
For example:</p>

<pre class="prettyprint lang-dart linenums:0 ">
#library('slider_sample');           // declare that this is a library.

#import('dart:html');                // it uses the html library...
#import('../ui_lib/view/view.dart'); // ...and a view library.

#source('SliderSample.dart');        // grab the code from SliderSample.dart.
</pre>


<p><aside class="note">
  <b>Note:</b>
  The string in the #library statement isn't currently used.
</aside>
</section></p>

<p><section id="libraries-private-members"></p>

<h4>Declaring private members</h4>

<p>If an identifier starts with an underscore,
it's private to its library.
For example,
in the following code, the Incrementer class
has an instance variable
called <code>_hiddenNum</code>.</p>

<pre class="prettyprint lang-dart linenums:0 ">
#library('HidingLibrary');

class Incrementer {
  num _hiddenNum = 0;
  
  void incrementNum() {
    _hiddenNum++;
  }
  
  void printNum() {
    print("The hidden number is $_hiddenNum");
  }
}

void main() {
  var o = new Incrementer();
  print("We can read _hiddenNum (${o._hiddenNum}).");
}
</pre>


<p>The main() method can refer to _hiddenNum
because it's in the same library as Incrementer.
But outside its library, _hiddenNum is invisible,
even to subclasses of Incrementer.</p>

<p>For example, the following code can't use _hiddenNum
because it's in a different library from Incrementer
(which is implemented in the library at <code>HidingLib/hider.dart</code>):</p>

<pre class="prettyprint lang-dart linenums:0 ">
#library('SubclassingLibrary');
#import('../HidingLib/hider.dart');

// this class is outside Incrementer's library, so it can't use _hiddenNum
class DoubleIncrementer extends Incrementer {
  void incrementNum() {
    //_hiddenNum = _hiddenNum + 2; // cannot resolve _hiddenNum
    super.incrementNum();          // the only way to increment _hiddenNum
    super.incrementNum();
  }
}
</pre>


<p></section></p>

<p><section id="libraries-summary"></p>

<h3>Summary of libraries and visibility</h3>

<p>Use <strong>#import</strong> if you need to use a library,
<strong>#source</strong> to pull files into a library,
and <strong>#library</strong> to declare that you're implementing a library.
Names prefixed with underscore (_) are private to the library.
</section></p>

<p></section></p>

</section>

<section>
  <h2 id="isolates">Isolates</h2>
  <p>All code in Dart runs in the context of an isolate.
Use additional isolates for concurrent programming,
and to run third-party code more securely.</p>

<h3>Isolate concepts</h3>

<p>Each isolate has its own heap, which means that all its values in memory,
including globals, are available only to that isolate. The only mechanism
available to communicate between isolates is to pass messages.
Messages are sent through ports.</p>

<p>The content of the message can be:</p>

<ul>
<li>A primitive value (null, num, bool, double, String)</li>
<li>An instance of SendPort</li>
<li>A list or map whose elements are any of the above, including other lists and maps</li>
<li>In <a href="#sending-any-type-of-object">special circumstances</a>, an object of any type</li>
</ul>


<p>List and maps can have cyclic references to themselves.
Each message is copied when sent to another isolate, ensuring
one isolate cannot change the state in another isolate.</p>

<p>Isolates might run in a separate process or thread, depending on the
implementation. For web applications, isolates can
be compiled to Web workers, if they are available.</p>

<h3>Using isolates</h3>

<p>To use an isolate, you import the isolates library,
spawn a new isolate, and then send and receive messages.</p>

<h4>Import the isolates library</h4>

<p>The isolates API can be found in the <code>dart:isolate</code> library.</p>

<pre class="prettyprint lang-dart linenums:0 ">
#import('dart:isolate');
</pre>


<h4>Spawn an isolate</h4>

<p>Any top-level function or static method
is a valid entry point for an isolate.
The entry point should not expect arguments and should return void.
It is illegal to use a function closure as an entry point to an isolate.
Pass the entry point to
<a href="http://api.dartlang.org/dart_isolate.html#spawnFunction">spawnFunction()</a>.</p>

<p><aside class="note">
<strong>Note:</strong> dart2js does not yet support static methods as isolate entry points.
</aside></p>

<pre class="prettyprint lang-dart linenums:0 ">
#import('dart:isolate');

runInIsolate() {
  print("hello from an isolate!");
}

main() {
  spawnFunction(runInIsolate);
}
</pre>


<p>We plan to support spawning an isolate from code at a URI.</p>

<h4>Send messages</h4>

<p>Send a message to an isolate via a
<a href="http://api.dartlang.org/dart_isolate/SendPort.html">SendPort</a>.
The spawnFunction() method returns a handle to its SendPort.</p>

<p>To simply send a message, use
<a href="http://api.dartlang.org/dart_isolate/SendPort.html#send">send()</a>.</p>

<pre class="prettyprint lang-dart linenums:0 ">
#import('dart:isolate');

echo() {
  // receive messages here, see next section
}

main() {
  SendPort sendPort = spawnFunction(echo);
  sendPort.send("Hello from main");
}
</pre>


<p><section id="sending-any-type-of-object"></p>

<h4>Send any type of object</h4>

<p>In special circumstances (such as when using spawnFunction() inside the Dart VM),
it is possible to send any type of object instance to an isolate.
The object message is copied when sent.</p>

<p>Sending arbitrary object instances to an isolate, even if
using spawnFunction(), is not yet available when compiling to
JavaScript.
</section></p>

<h4>Receive messages</h4>

<p>Use a <a href="http://api.dartlang.org/dart_isolate/ReceivePort.html">ReceivePort</a>
to receive messages sent to an isolate. Obtain a handle to the ReceivePort
from the <a href="http://api.dartlang.org/dart_isolate.html#get:port">port</a>
property. Then, handle a new message with a
callback function passed to the
<a href="http://api.dartlang.org/dart_isolate/ReceivePort.html#receive">receive()</a>
method.</p>

<pre class="prettyprint lang-dart linenums:0 ">
#import('dart:isolate');

echo() {
  port.receive((msg, SendPort reply) {
    print("I received: $msg");
  });
}

main() {
  SendPort sendPort = spawnFunction(echo);
  sendPort.send("Hello from main");
}
</pre>


<h4>Receive a reply</h4>

<p>Use the <a href="http://api.dartlang.org/dart_isolate/SendPort.html#call">call()</a>
method on SendPort as a simple way to send a
message and receive a reply. The call() method returns a <a href="http://api.dartlang.org/dart_core/Future.html">Future</a> for the reply.</p>

<pre class="prettyprint lang-dart linenums:0 ">
#import('dart:isolate');

echo() {
  port.receive((msg, SendPort reply) {
    reply.send("I received: $msg");
  });
}

main() {
  SendPort sendPort = spawnFunction(echo);
  sendPort.call("Hello from main").then((reply) {
    print(reply);    // I received: Hello from main
  });
}
</pre>


</section>

<section>
  <h2 id="typedefs">Typedefs</h2>
  <p>In Dart, functions are objects, just as strings and numbers.
A <em>typedef</em>, or <em>function-type alias</em>, gives a function type a
name that you can use when declaring fields and return
types. A typedef retains type information
when a function type is assigned to a variable.</p>

<p>Consider the following code, which does not use a typedef.</p>

<pre class="prettyprint lang-dart linenums:0 ">
class SortedCollection {
  Function compare;

  SortedCollection(int f(Object a, Object b)) {
    compare = f;
  }
}

int sort(Object a, Object b) => ... ;

main() {
  SortedCollection collection = new SortedCollection(sort);

  // all we know is that compare is a function, but what type of function?
  print(collection.compare is Function);  // true
}
</pre>


<p>Type information is lost when assigning <code>f</code> to <code>compare</code>.
The type of <code>f</code> is <code>(Object, Object) → int</code>, yet
the type of <code>compare</code> is Function.
If we change the code to use explicit names and retain type information,
both developers and tools can use that information.</p>

<p>Adding a typedef lets Dart retain the type information.</p>

<pre class="prettyprint lang-dart linenums:0 ">
<b>typedef int Compare(Object a, Object b);</b>

class SortedCollection {
  Compare compare;

  SortedCollection(this.compare);
}

int sort(Object a, Object b) => ... ;

main() {
  SortedCollection collection = new SortedCollection(sort);
  print(collection.compare is Function);  // true
  print(collection.compare is Compare);   // true
}
</pre>


<p><aside class="note">
<strong>Note:</strong> Currently, typedefs are restricted to function types.
This may change in a future version of the language specification.
</aside></p>

<p>As typedefs are simply aliases, they offer a way to check the
type of any function. For example:</p>

<pre class="prettyprint lang-dart linenums:0 ">
typedef int Compare(int a, int b);

int sort(int a, int b) => a - b;

main() {
  print(sort is Compare);  // true!
}
</pre>


<p>Typedefs can be parameterized.</p>

<pre class="prettyprint lang-dart linenums:0 ">
typedef int Compare&lt;T>(T a, T b);

class SortedCollection&lt;T> {
  Compare&lt;T> compare;
  SortedCollection(this.compare);
}

main() {
  SortedCollection&lt;int> s = new SortedCollection&lt;int>((a,b) => a - b);
  print(s.compare is Compare&lt;int>);  // true
  print(s.compare('a','b'));  // checked mode throws exception
}
</pre>


</section>

<section>
  <h2 id="comments">Comments</h2>
  <p>Dart supports single-line comments, multi-line comments,
and documentation comments.</p>

<h3>Single-line comments</h3>

<p>A single-line comment begins with <code>//</code>.
Everything between <code>//</code> and the end of line
is ignored by the Dart compiler.</p>

<pre class="prettyprint lang-dart linenums:0 ">
main() {
  // TODO: refactor into an AbstractLlamaGreetingFactory ?
  print("Welcome to my Llama farm!");
}
</pre>


<h3>Multi-line comments</h3>

<p>A multi-line comment begins with <code>/*</code> and ends with <code>*/</code>.
Everything between <code>/*</code> and <code>*/</code> is ignored by the
Dart compiler (unless the comment is a documentation comment, see below).
Multi-line comments can nest.</p>

<pre class="prettyprint lang-dart linenums:0 ">
main() {
  /*
   * This is a lot of work. Consider raising chickens.

  Llama larry = new Llama();
  larry.feed();
  larry.exercise();
  larry.clean();
   */
}
</pre>


<h3>Documentation comments</h3>

<p>Documentation comments are multi-line comments that begin
with <code>/**</code>. Inside a documentation comment, the Dart
compiler ignores all text unless it is enclosed in brackets.
Using brackets, you can embed links to classes, methods,
and fields into your comments. The names in brackets are resolved to the
lexical scope of the documented program element.</p>

<p>Here is an example of documentation comments with references
to other classes and arguments:</p>

<pre class="prettyprint lang-dart linenums:0 ">
/**
 * The llama (Lama glama) is a domesticated South American
 * camelid, widely used as a meat and pack animal by Andean
 * cultures since pre-Hispanic times.
 */
class Llama {
  String name;

  /**
   * Feed your llama [Food]. Typically, one bale of hay per week.
   */
  feed(Food food) {
    ...
  }

  /**
   * Exercise your llama with an [activity] for [timeLimit] minutes.
   */
  exercise(Activity activity, int timeLimit) {
    ...
  }
}
</pre>


<p>You can use the dartdoc utility, bundled in the SDK, to parse
Dart code and generate HTML. An example of dartdoc output
follows.</p>

<pre class="prettyprint lang-html linenums:0 ">
&lt;div class="doc">
&lt;p>Feed your llama &lt;a class="crossref" href="../llama/Food.html">Food&lt;/a>. Typically, one bale of hay per week.&lt;/p>
&lt;pre class="source">
feed(Food food) {
  // ...
}
&lt;/pre>
&lt;/div>
</pre>


<p>Notice how <code>[Food]</code> from the documentation comments
is converted to an HTML link to the API docs for the Food class.</p>

</section>

<script async type="text/javascript"
  src="http://try.dartlang.org/dartboard.dart.app.js">
</script>

<link href="/css/style.css" type="text/css" rel="stylesheet">
<link href="/css/prettify.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="/js/prettify.js"></script>
<script>
window.addEventListener("load", function() {
  prettyPrint();
})
</script>

			</article>
		</div>
		
		<footer>
			<p>
			  Except as otherwise <a href="http://code.google.com/policies.html#restrictions">noted</a>, the content of this page is licensed under the <a 		href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 License</a>, and code samples are licensed under the <a href="http://code.google.com/google_bsd_license.html">BSD License</a>.
			</p>
			<p>
				<a href="/tos.html" style="border-right: 1px solid black; padding-right: 5px">Terms of Service</a>
				<a href="http://www.google.com/intl/en/privacy/privacy-policy.html">Privacy Policy</a>
			</p>
	</footer>

	</div>

	<!--[if lt IE 7 ]>
	<script src="js/dd_belatedpng.js"></script>
	<script> DD_belatedPNG.fix('img, .png_bg');</script>
	<![endif]-->

</body>
</html>

